import numpy as np
import dill
import tkinter as tk
from tkinter import ttk
class TreeViewApp:
    def __init__(self, root):
        self.root = root
        self.root.title("树形结构示例")

        self.b=ttk.Button(master=root,text='显示节点',command=self.show_node)
        # self.b.bind("<Button-1>",self.show_node)
        self.b.grid(row=0,column=1)
        # 创建 Treeview 控件
        self.tree = ttk.Treeview(root,show='tree',selectmode='browse')
        self.tree.grid(row=0,column=0)

        # 定义树形结构的数据
        with open("L:\\EF2D\\tests\\result\\job-c3d8-.dill",'rb') as f:
            data=dill.load(f)
        # 构建树形结构
        self.build_tree(data, "", 0)

        # 绑定右键点击事件
        self.tree.bind("<Button-3>", self.on_right_click)
    def show_node(self):
        item=self.tree.selection()[0]
        print(f"now node item={item}")
        print(f"now node item values={self.tree.item(item,'values')}")
    def build_tree(self, data, parent='', level=0):
        val=0
        for key, value in data.items():
            if key.startswith('__'):
                continue
            if isinstance(value,dict):
                val=0
            # if level == 0:
            #     iid = self.tree.insert(parent, 'end', text=key)
            # else:
            iid = self.tree.insert(parent, 'end', text=key)
            # self.tree.insert(iid, 'end', text="子节点")
            if isinstance(value,dict):
                self.build_tree(value, iid, level + 1)

    def on_right_click(self, event):
        # 获取鼠标点击位置的节点
        # item = self.tree.identify_row(event.y)
        item=self.tree.selection()[0]
        if item:
            # 选中该节点
            self.tree.selection_set(item)
            # 创建右键菜单
            menu = tk.Menu(self.root, tearoff=0)
            menu.add_command(label="GF", command=lambda: self.on_menu_command(item))
            # 显示菜单
            menu.post(event.x_root, event.y_root)

    def on_menu_command(self, item):
        # 获取选中节点的标签
        label = self.tree.item(item, "values")
        # 在控制台打印标签
        print(f"选中的节点标签: {label}")

if __name__ == "__main__":
    root = tk.Tk()
    app = TreeViewApp(root)
    root.mainloop()
